import { getData } from '@vimi/utils-api'
import { SERVICE_NAME } from '@/gov/plugins/constant'

const state = {
  govTaskCount: {},
}

const getters = {
  govTaskCount: state => state.govTaskCount,
}

const actions = {
  async getMyTaskCount({ commit, rootGetters }, force = true) {
    if (!force && state.govTaskCount.noArchive) {
      return Promise.resolve(state.govTaskCount)
    }

    const res = await getData(
      SERVICE_NAME,
      'task_list',
      {
        'orWhere.address_code.endlike': rootGetters.user.queryAddressCode.replace(/0*$/g, ''),
        'orWhere.task_person.like': rootGetters.user.userId,
        'task_status.eq': 0,
        'submit_type.eq': 1,
        groupFields: 'task_type',
        fields: ['task_type'],
        groupFunc: 'count(task_list.task_type)',
      },
      {
        N1task_type: 'ASC',
      }
    )

    const process = await getData(
      SERVICE_NAME,
      'task_list',
      {
        'orWhere.address_code.endlike': rootGetters.user.queryAddressCode.replace(/0*$/g, ''),
        'orWhere.task_person.like': rootGetters.user.userId,
        'task_status.eq': 1,
        'submit_type.eq': 1,
        groupFields: 'task_type',
        fields: ['task_type'],
        groupFunc: 'count(task_list.task_type)',
      },
      {
        N1task_type: 'ASC',
      }
    )
    const processData = (process && process.data) || []
    const resData = (res && res.data) || []
    let data = {}
    resData.forEach(item => {
      data[item.task_type] = {
        num: item.p || 0,
      }
    })
    processData.forEach(item => {
      if (data[item.task_type]) {
        data[item.task_type].process = item.p || 0
      } else {
        data[item.task_type] = {
          num: 0,
          process: item.p || 0,
        }
      }
    })
    commit('govTaskCount', data)
    return data
  },
}

const mutations = {
  govTaskCount: (state, payload) => (state.govTaskCount = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
